// Service Worker for Gemini Response Downloader Extension

// Listen for the browser action (button) click
chrome.action.onClicked.addListener((tab) => {
  console.log("Action button clicked on tab:", tab.id, "URL:", tab.url); // Log click
  // Check if the clicked tab's URL is a Gemini page
  if (tab.url && tab.url.startsWith("https://gemini.google.com/")) { // Make the check more general
    console.log("URL matches Gemini. Sending message..."); // Log URL match
    // Send a message to the content script in the active tab
    chrome.tabs.sendMessage(tab.id, { action: "scanGeminiResponses" }, (response) => {
      if (chrome.runtime.lastError) {
        // Handle potential errors, e.g., content script not ready yet
        console.error("Error sending message to content script:", chrome.runtime.lastError.message); // Use error for clarity
        // Optionally, you could try injecting the script here if it failed,
        // but usually relying on manifest injection is cleaner.
        // chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] });
      } else {
        // Optional: Log success or handle response from content script
         console.log("Scan message sent successfully. Response from content script:", response); // Log success and response
      }
    });
  } else {
    console.log("Button clicked, but URL does not match Gemini:", tab.url); // Log URL mismatch
    // Optionally disable the button on non-matching pages via manifest or dynamically
  }
});

// Optional: Log when the service worker starts (useful for debugging)
console.log("Gemini Downloader background script started.");